package nl.ru.rd.facedetection.nnbfd;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;

import nl.ru.rd.facedetection.nnbfd.neuralnetwork.NeuralNetwork;

/**
 * Grades a Neural Network using a Testset. Specific class for a test in a paper.
 * 
 * @author Wouter Geraedts (s0814857)
 */
public class Grader
{
	private ArrayList<LearnSet> gradeSet;

	public Grader()
	{
		this.initializeList();
	}

	private void initializeList()
	{
		this.gradeSet = new ArrayList<LearnSet>(2000);

		String directoryPath = "/media/data/web/web/test/";
		File directory = new File(directoryPath);
		for(String file : directory.list())
		{
			String filePath = directoryPath + file;
			BufferedImage image = null;
			try
			{
				image = ImageIO.read(new File(filePath));
				Matrix matrix = Preprocessor.toMatrix(image);

				Preprocessor.equalize(matrix);
				this.gradeSet.add(new LearnSet(matrix, new double[] { 1.0 }));
			} catch (IOException e)
			{
				e.printStackTrace();
				return;
			}
		}

		File faalDirectory = new File("faal/");
		for(String file : faalDirectory.list())
		{
			String filePath = "faal/" + file;
			BufferedImage image = null;

			try
			{
				image = ImageIO.read(new File(filePath));
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Matrix matrix = Preprocessor.toMatrix(image);
			this.gradeSet.add(new LearnSet(matrix, new double[] { 0.0 }));
		}
	}

	public double grade(NeuralNetwork network)
	{
		double result = 0.0;
		for(LearnSet set : this.gradeSet)
		{
			double realResult = network.calculate(set.matrix)[0];
			double expectedResult = set.expectedResult[0];

			double absResult = Math.abs(realResult - expectedResult);
			result += absResult;
		}

		result /= (double) this.gradeSet.size();
		return result;
	}

	public static void main(String[] args)
	{
		Grader grader = new Grader();

		for(int i = 0; i < 1000; i++)
			System.out.println(grader.grade(NeuralNetwork.readFromFile("networks/network" + i)));
	}
}
